package com.gitee.sys.service.impl;


import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.mybase.top.entity.SysUser;
import com.gitee.mybase.top.enums.TokenType;
import com.gitee.mybase.top.util.DateUtil;
import com.gitee.mybase.top.util.JwtUtil;
import com.gitee.sys.mapper.SysUserMapper;
import com.gitee.sys.pojo.LoginResult;
import com.gitee.sys.pojo.LoginUser;
import com.gitee.sys.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chengkaimao
 * @since 2018-11-17
 */
@Service
@Component
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Override
    public IPage<SysUser> getPage(long current, long size, SysUser sysUser) {
        IPage<SysUser> page = new Page<>(current, size);
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(sysUser.getAccount())){
            sysUserQueryWrapper.like("account", sysUser.getAccount());
        }
        if(StringUtils.isNotEmpty(sysUser.getPhone())){
            sysUserQueryWrapper.like("phone", sysUser.getPhone());
        }
        if(StringUtils.isNotEmpty(sysUser.getShopCode())){
            sysUserQueryWrapper.eq("shop_code", sysUser.getShopCode());
        }
        if(StringUtils.isNotEmpty(sysUser.getCname())){
            sysUserQueryWrapper.like("cname", sysUser.getCname());
        }

        page = this.page(page, sysUserQueryWrapper);
        return page;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveUser(SysUser sysUser) {
        sysUser.setCreateTime(LocalDateTime.now());
        sysUser.setSecret(UUID.randomUUID().toString().replace("-", "").toUpperCase());
        sysUser.setPassword(JwtUtil.encrypt(sysUser.getPassword(), sysUser.getSecret()));
        sysUser.setIsLock(0);
        sysUser.setIsValid(1);
        return baseMapper.insert(sysUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysUser sysUser) {
        UpdateWrapper<SysUser> sysUserUpdateWrapper = new UpdateWrapper<>();
        sysUserUpdateWrapper.set("cname", sysUser.getCname());
        sysUserUpdateWrapper.set("head_icon", sysUser.getHeadIcon());
        sysUserUpdateWrapper.set("link_addr", sysUser.getLinkAddr());
        sysUserUpdateWrapper.set("update_time", LocalDateTime.now());
        sysUserUpdateWrapper.eq("account", sysUser.getAccount());
        return baseMapper.update(sysUser, sysUserUpdateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delUser(String account) {
       QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
       queryWrapper.eq("account", account);
       return baseMapper.delete(queryWrapper);

    }

    @Override
    public LoginResult login(LoginUser loginUser) {
        LoginResult loginResult = new LoginResult();
        if("account".equals(loginUser.getType())){
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("account", loginUser.getAccount());
            SysUser user = baseMapper.selectOne(queryWrapper);

            String token;
            String tokenType;
            if(user == null){
                loginResult.setSeccess(false);
                loginResult.setError("账号不存在");
                return loginResult;
            }

            if(user.getIsLock() == 1){
                loginResult.setSeccess(false);
                loginResult.setError("账号已锁定");
                return loginResult;
            }

            if(!user.getPassword().equals(JwtUtil.encrypt(loginUser.getPassword(),user.getSecret()))){
                loginResult.setSeccess(false);
                loginResult.setError("账号或密码错误");
                return loginResult;
            }

            if(loginUser.getAutoLogin()){
                tokenType = TokenType.LOCAL.getValue();
            }else{
                tokenType = TokenType.SESSION.getValue();
            }
            try{
                loginResult.setSeccess(true);
                loginResult.setRememberme(loginUser.getAutoLogin());
                loginResult.setAccount(user.getAccount());
                loginResult.setIcon(user.getHeadIcon());
                loginResult.setUsername(user.getCname());
                loginResult.setToken(JwtUtil.sign(user.getSecret(),
                        user.getAccount(),
                        new Date(),
                        DateUtil.localTimeToDate(user.getJwtExp()),
                        DateUtil.localTimeToDate(user.getJwtNbf()),
                        tokenType));
                loginResult.setRedirect("http://www.baidu.com");
                return loginResult;
            }catch (Exception e){
                e.printStackTrace();
                loginResult.setSeccess(false);
                loginResult.setError("签证失败");
                return loginResult;
            }
        }else{
            loginResult.setSeccess(false);
            loginResult.setError("暂不支持");
            return loginResult;
        }


    }

}
